package etnorservice.etnor_service.controller;

import etnorservice.etnor_service.domain.po.LoginAndRegister;
import etnorservice.etnor_service.domain.po.User;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.EmailService;
import etnorservice.etnor_service.service.UserService;

import etnorservice.etnor_service.service.VerificationCodeService;
import etnorservice.etnor_service.utils.AesUtil;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    VerificationCodeService verificationCodeService;
    @Autowired
    EmailService mailService;
//    @Autowired
//    RedisTokenManager redisTokenManager;

    @Value("${jwt.secret}")
    private String jwtSecret;

    @PostMapping("/admin/login")
    public Result login(@RequestBody LoginAndRegister loginAndRegister) throws Exception {

        User user = new User();
        user.setAccount(loginAndRegister.getAccount());
        user.setPassword(loginAndRegister.getPassword());
        Result result = new Result();

        List<User> userList = userService.findUserByAccountAndPassword(user);
        if (userList.size() != 0) {
            User foundUser = userList.get(0);
            if (foundUser.getStatus() == 0) {
                result.setCode(20001);
                result.setMessage("登录失败，账号异常");
            } else if (foundUser.getStatus() == 1) {
//                if(foundUser.getRole()==0) {
//                    result.setMessage("HASH-ETNOR-BASE?cto");
//                }else{
//                    result.setMessage("CANIFIA-SPUER-lp???");
//                }
                    result.setCode(20002);
                    result.setMessage("登录成功");

                // 生成token
                String token = generateToken(foundUser);

                result.setData(token);
//                redisTokenManager.saveToken(token);
                 result.setCurrentMode(foundUser.getAccount());

            }
        } else {
            result.setCode(400);
            result.setMessage("登录失败，用户不存在");
        }
        return result;
    }

    private String generateToken(User user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 60 * 60 * 1000); // 有效期1小时

        return Jwts.builder()
                .setSubject(user.getAccount())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }
    @GetMapping("/system/role")
    public Result getRole(@RequestHeader(value = "Authorization", required = false)
                                      String authorizationHeader){
        Result result=new Result();
        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        int role=userService.findRoleByAccount(Integer.parseInt(account)).getRole();
        if(role==0){
            result.setCode(20001);
        }
        if(role==1){
            result.setCode(20002);
        }

        return result;
    }
    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }
    @PostMapping("/register")
    public Result registerUser(@RequestBody LoginAndRegister loginAndRegister){
        Result result=new Result();

        // 验证验证码
        if (!verificationCodeService.verifyCode(loginAndRegister.getEmail(), loginAndRegister.getCode())) {
            return Result.error("验证码错误或已过期");
        }
        if(userService.findRoleByAccount(Integer.parseInt(loginAndRegister.getAccount()))!=null){
            return Result.error("账号已存在，注册失败!");
        }

        try {
            // 注册用户
            userService.registerUser(loginAndRegister);

            // 发送注册成功邮件
            mailService.sendRegistrationSuccessEmail(loginAndRegister);

            return Result.success("注册成功，请查收注册成功邮件");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("注册失败：" + e.getMessage());
        }
    }
}
